﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using YaP.Library.Extensions;

namespace YaP.Library.mircLib
{
    internal class AliasParser
    {
        private readonly TextFile AliasFile;
        private string[] lines;

        public AliasParser(string filepath)
        {
            AliasFile = new TextFile(filepath);
            AliasFile.Open();
            lines = AliasFile.Lines;
            AliasFile.Close();
        }

        public AliasParser()
        {
        }

        public SerializableDictionary<string, AliasDesc> Dictionnary
        {
            get { return Parse(); }
        }

        public void SetText(string Text)
        {
            lines = Text.Split(Environment.NewLine.ToCharArray());
        }

        private SerializableDictionary<string, AliasDesc> Parse()
        {
            SerializableDictionary<string, AliasDesc> toreturn = new SerializableDictionary<string, AliasDesc>();
            Regex SimpleAliasRegex =
                new Regex(@"^(alias\s|\x2F)([a-zA-Z0-9]+)\s+(((.*)(\x24\w))*([a-zA-Z0-9]*)(\s)*)*$", RegexOptions.Compiled | RegexOptions.Singleline);
            for (var i = 0; i < lines.Length; i++)
            {
                var str = lines[i];
                var m = SimpleAliasRegex.Match(str);
                if (!m.Success)
                    throw new SyntaxEception("Syntax error line " + (i + 1));
                string RfcExpression = m.Groups[4].Value;
                AliasDesc toadd = new AliasDesc();
                toadd.Type = AliasType.RFC2812;
                toadd.Expression = RfcExpression;
                try
                {
                    toreturn.Add(m.Groups[2].Value, toadd);
                }
                catch (ArgumentException)
                {
                    throw new SyntaxEception("Multiple definition on line:" + (i + 1));
                }
            }
            return toreturn;
        }
    }
}